﻿using System;
using System.Runtime.Caching;
namespace Composr
{
    public static class Cache
    {
        private static ObjectCache cache = null;
        private static CacheItemPolicy policy = null;

        static Cache()
        {
            InitializeCache();
            policy = new CacheItemPolicy() {
                AbsoluteExpiration = DateTimeOffset.Now.AddHours(1),
                Priority = CacheItemPriority.Default
            };
        }

        private static void InitializeCache()
        {
            var oldcache = cache;
            cache = new MemoryCache(DateTime.Now.ToLongDateString());
        }

        /// <summary>
        /// stores the item in the cache with the provided key
        /// </summary>
        /// <param name="key"></param>
        /// <param name="item"></param>
        public static void Add<T>(string key, T item)
        {
            cache.Set(key, item, policy);
        }

        /// <summary>
        /// removes an item from the cache
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            cache.Remove(key);
        }

        /// <summary>
        /// returns an item that matches the key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            if (cache.Contains(key) && cache.Get(key).GetType() == typeof(T))
            {
                return (T)cache.Get(key);
            }
            return default(T);
        }

        /// <summary>
        /// whether the cache contains an entry with the specified key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Contains(string key)
        {
            return cache.Contains(key);
        }       
 
        public static void Clear()
        {
            InitializeCache();
        }
    }
}
